﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _4mvcBlog.Core
{
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        public PagedList(IList<T> source, int index, int pageSize, int totalItemCount)
        {
            Initialize(source, index, pageSize, totalItemCount);
        }

        #region IPagedList Members

        public int PageCount { get; private set; }
        public int TotalItemCount { get; private set; }
        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }
        public bool HasPreviousPage { get; private set; }
        public bool HasNextPage { get; private set; }
        public bool IsFirstPage { get; private set; }
        public bool IsLastPage { get; private set; }

        #endregion

        protected void Initialize(IList<T> source, int index, int pageSize, int totalItemCount)
        {
            //### set source to blank list if source is null to prevent exceptions
            if (source == null)
                source = new List<T>();

            //### set properties
            TotalItemCount = totalItemCount;
            PageSize = pageSize;
            PageIndex = index;
            if (TotalItemCount > 0)
                PageCount = (int)Math.Ceiling(TotalItemCount / (double)PageSize);
            else
                PageCount = 0;
            HasPreviousPage = (PageIndex > 1);
            HasNextPage = (PageIndex < PageCount);
            IsFirstPage = (PageIndex <= 1);
            IsLastPage = (PageIndex >= PageCount);

            //### argument checking
            if (index < 1)
                throw new ArgumentOutOfRangeException("PageIndex不可以小于1.");
            if (pageSize < 1)
                throw new ArgumentOutOfRangeException("PageSize不可以小于1.");

            //### 将数据源添加到内部列表
            if (TotalItemCount > 0)
                AddRange(source);
        }
    }
}
